<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPage, create, updatebyid, deletebyid } from '@/api/venue'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'

// 表格数据相关
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  city: '',
  status: ''
})

// 新增表单
const addDialogVisible = ref(false)
const addForm = reactive({
  venuesName: '',
  city: '',
  position: '',
  performs: 0
})
const addFormRef = ref(null)

// 编辑表单
const editDialogVisible = ref(false)
const editForm = reactive({
  venuesId: '',
  venuesName: '',
  city: '',
  position: '',
  performs: 0
})
const editFormRef = ref(null)

// 表单验证规则
const rules = {
  venuesName: [{ required: true, message: '请输入场地名称', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  position: [{ required: true, message: '请输入具体位置', trigger: 'blur' }],
  performs: [{ required: true, message: '请输入演出场次', trigger: 'blur' }]
}

// 状态选项
const statusOptions = [
  { value: 'upcoming', label: '未演出', type: 'success' },
  { value: 'ongoing', label: '进行中', type: 'warning' },
  { value: 'finished', label: '已结束', type: 'info' }
]

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)

// 数据加载方法
const loadData = async () => {
  loading.value = true
  try {
    const res = await getPage(
      currentPage.value - 1,
      pageSize.value,
      searchForm.city || ''
    )
    if (res.code === 1 && res.data) {
      tableData.value = mapDataToTable(res.data.data)
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 新增场地
const handleAdd = () => {
  addDialogVisible.value = true
}

const submitAddForm = async () => {
  if (!addFormRef.value) return

  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await create(addForm)
        if (res.code === 1) {
          ElMessage.success('新增成功')
          addDialogVisible.value = false
          loadData()
        } else {
          ElMessage.error(res.msg || '新增失败')
        }
      } catch (error) {
        console.error(error)
        ElMessage.error('新增失败')
      }
    }
  })
}

// 编辑场地
const handleEdit = (row) => {
  Object.assign(editForm, {
    venuesId: row.id,
    venuesName: row.venuesName,
    city: row.venuesCity,
    position: row.position,
    performs: row.performs
  })
  editDialogVisible.value = true
}

const submitEditForm = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log(editForm)

        const res = await updatebyid(editForm)
        if (res.code === 1) {
          ElMessage.success('修改成功')
          editDialogVisible.value = false
          loadData()
        } else {
          ElMessage.error(res.msg || '修改失败')
        }
      } catch (error) {
        console.error(error)
        ElMessage.error('修改失败')
      }
    }
  })
}

// 删除场地
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该场地信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deletebyid(row.id)
        if (res.code === 1) {
          ElMessage.success('删除成功')
          loadData()
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      } catch (error) {
        console.error(error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 搜索和重置
const onSubmit = () => {
  currentPage.value = 1
  loadData()
}

const onReset = () => {
  searchForm.city = ''
  searchForm.status = ''
  currentPage.value = 1
  loadData()
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

// 重置表单
const resetForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 数据映射方法
const mapDataToTable = (data) => {
  return data.map((item) => {
    const createTime = new Date(
      item.createTime[0],
      item.createTime[1] - 1,
      item.createTime[2]
    )
    const updateTime = new Date(
      item.updateTime[0],
      item.updateTime[1] - 1,
      item.updateTime[2]
    )

    let status = 'upcoming'
    if (parseInt(item.performs) === 0) {
      status = 'finished'
    }

    return {
      id: item.venuesId,
      performName: item.venuesName,
      venuesName: item.venuesName,
      venuesCity: item.city,
      position: item.position,
      performs: parseInt(item.performs) || 0,
      status,
      createTime: createTime.toLocaleDateString(),
      updateTime: updateTime.toLocaleDateString(),
      remark: `位于${item.position}的${item.venuesName}，共有${item.performs}场演出`
    }
  })
}
// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>
<template>
  <el-card class="box-card">
    <!-- 页面头部 -->
    <template #header>
      <div class="clearfix">
        <span>演出场地信息</span>
        <el-button
          type="primary"
          :icon="Plus"
          @click="handleAdd"
          style="float: right; margin-left: 10px"
        >
          新增场地
        </el-button>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline mb-4">
      <el-form-item label="演出城市">
        <el-input v-model="searchForm.city" placeholder="城市名"></el-input>
      </el-form-item>
      <el-form-item label="演出状态">
        <el-select
          v-model="searchForm.status"
          placeholder="全部状态"
          clearable
          class="status-select"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span class="flex items-center">
              <el-tag
                :type="item.type"
                size="small"
                effect="plain"
                class="option-tag"
              >
                {{ item.label }}
              </el-tag>
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-space>
          <el-button type="primary" :icon="Search" @click="onSubmit"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="onReset">重置</el-button>
        </el-space>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      :header-cell-style="{ backgroundColor: '#f5f7fa' }"
    >
      <el-table-column label="序号" width="80">
        <template #default="scope">
          <span>{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="performName"
        label="场地名称"
        width="250"
      ></el-table-column>
      <el-table-column
        prop="venuesCity"
        label="城市"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="position"
        label="具体位置"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="performs"
        label="演出场次"
        width="100"
      ></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag
            :type="
              statusOptions.find((item) => item.value === scope.row.status)
                ?.type
            "
          >
            {{
              statusOptions.find((item) => item.value === scope.row.status)
                ?.label
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        show-overflow-tooltip
      ></el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" type="warning" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button size="small" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex justify-end mt-4">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 新增场地对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增场地"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="场地名称" prop="venuesName">
          <el-input v-model="addForm.venuesName"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="addForm.city"></el-input>
        </el-form-item>
        <el-form-item label="具体位置" prop="position">
          <el-input v-model="addForm.position"></el-input>
        </el-form-item>
        <el-form-item label="演出场次" prop="performs">
          <el-input-number
            v-model="addForm.performs"
            :min="0"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑场地对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑场地"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="场地名称" prop="venuesName">
          <el-input v-model="editForm.venuesName"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="editForm.city"></el-input>
        </el-form-item>
        <el-form-item label="具体位置" prop="position">
          <el-input v-model="editForm.position"></el-input>
        </el-form-item>
        <el-form-item label="演出场次" prop="performs">
          <el-input-number
            v-model="editForm.performs"
            :min="0"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
.box-card {
  margin: 20px;
}
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
.box-card {
  margin: 20px;
}

.status-select {
  width: 180px;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select-dropdown__item) {
  height: 34px;
  line-height: 34px;
}

.inline-flex {
  display: inline-flex;
  align-items: center;
}

.mr-2 {
  margin-right: 8px;
}
</style>
